/**
 * 
 */
package com.nishop.service;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import com.google.common.base.Splitter;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.nishop.api.IGoodsService;
import com.nishop.api.common.CharacterConstant;
import com.nishop.api.common.NiShopConfig;
import com.nishop.api.common.NiShopConstant;
import com.nishop.api.entity.Category;
import com.nishop.api.entity.CategoryExample;
import com.nishop.api.entity.Goods;
import com.nishop.api.entity.GoodsExample;
import com.nishop.api.form.GoodsRequestForm;
import com.nishop.api.layui.entity.TreeNode;
import com.nishop.api.util.FileUtil;
import com.nishop.api.util.Identity;
import com.nishop.service.dao.CategoryMapper;
import com.nishop.service.dao.GoodsMapper;

/**
 * @author liuwenlai
 *
 */
@Service
public class GoodsServiceImpl implements IGoodsService {

	@Autowired
	private GoodsMapper goodsMapper;

	@Autowired
	private CategoryMapper categoryMapper;

	@Autowired
	private NiShopConfig config;

	@Value("${nishop.httpd.goods.image}")
	private String goodsImagePath;

	@Override
	public List<Goods> queryGoodsList(GoodsRequestForm goodsRequestForm) {

		Map<String, Object> param = Maps.newHashMap();

		if (goodsRequestForm.getPage() != null && goodsRequestForm.getLimit() != null) {
			param.put("start", (goodsRequestForm.getPage() - 1) * goodsRequestForm.getLimit());
			param.put("limit", goodsRequestForm.getLimit());
		}
		if (StringUtils.isNotBlank(goodsRequestForm.getGoodsName())) {
			param.put("goodsName", goodsRequestForm.getGoodsName());
		}
		List<Goods> goods = goodsMapper.queryGoodsByPage(param);

		return goods;
	}

	@Override
	public long queryGoodsCount(GoodsRequestForm goodsRequestForm) {

		GoodsExample example = new GoodsExample();
		if (StringUtils.isNotBlank(goodsRequestForm.getGoodsName())) {
			example.createCriteria().andNameLike("%" + goodsRequestForm.getGoodsName() + "%");
		}
		long count = goodsMapper.countByExample(example);

		return count;
	}

	@Override
	public String uploadGoodsImages(CommonsMultipartFile file) throws IOException {
		String uuid = Identity.uuidWithoutHyphen();
		String filePath = config.goodsImagePath + File.separator + uuid + File.separator;
		File fileDir = new File(filePath);
		if (!fileDir.exists()) {
			fileDir.mkdirs();
		}
		String fileName = file.getOriginalFilename();
		File imageFile = new File(filePath + fileName);
		FileUtil.writeFile(imageFile, file.getInputStream());
		String requestUrl = goodsImagePath;
		return requestUrl + uuid + File.separator + fileName;
	}

	@Override
	public boolean addGoods(Goods goods) {
		goods.setId(Identity.uuidWithoutHyphen());
		return goodsMapper.insertSelective(goods) > 0;
	}

	@Override
	public boolean editGoods(Goods goods) {
		GoodsExample example = new GoodsExample();
		example.createCriteria().andIdEqualTo(goods.getId());
		return goodsMapper.updateByExampleSelective(goods, example) > 0;
	}

	@Override
	public List<TreeNode> queryAttrTreeData(GoodsRequestForm goodsRequestForm) {

		CategoryExample base = new CategoryExample();
		List<Category> categories = categoryMapper.selectByExample(base);

		return this.convertTreeData(categories, goodsRequestForm.getAttributeId());
	}

	private List<TreeNode> convertTreeData(List<Category> categories, String selectedId) {
		List<TreeNode> treeNodes = Lists.newArrayList();
		List<TreeNode> parent = Lists.newArrayList();
		for (Category categorie : categories) {
			TreeNode node = new TreeNode();
			node.setId(categorie.getId());
			node.setName(categorie.getName());
			node.setParentId(categorie.getParentId());
			if (StringUtils.equals(selectedId, categorie.getId())) {
				node.setChecked(true);
			}
			treeNodes.add(node);
			if (StringUtils.equals(NiShopConstant.ROOT, categorie.getParentId())) {
				parent.add(node);
			}
		}

		for (TreeNode treeNode : parent) {
			this.generateTree(treeNode, treeNodes);
		}
		return parent;
	}

	private void generateTree(TreeNode treeNode, List<TreeNode> treeNodes) {
		for (TreeNode node : treeNodes) {
			if (StringUtils.equals(treeNode.getId(), node.getParentId())) {
				generateTree(node, treeNodes);
				treeNode.getChildren().add(node);
			}
		}
	}

	@Override
	public boolean delGoods(Goods goods) {
		if (StringUtils.isNotBlank(goods.getId())) {
			List<String> ids = Splitter.on(CharacterConstant.CHARACTER_COMMA_EN)
					.splitToList(goods.getId());
			GoodsExample example = new GoodsExample();
			example.createCriteria().andIdIn(ids);
			return goodsMapper.deleteByExample(example) > 0;
		}
		return false;
	}

}
